<template>
  <view class="topl">
    <image :src="`${store.imgDomain}my_data_top.png`" mode="scaleToFill" />
  </view>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" :isLeft="true" color="#fff">
      <template #title><text style="color: #fff">个人资料</text></template>
    </GlobalTopBar>
    <view class="page_content">
      <!-- 顶部信息 -->
      <view class="topinfo">
        <image
          @click="imgFun"
          class="hadeimg"
          :src="store.userInfo?.headimg || `${store.imgDomain}my_hade.png`"
          mode="scaleToFill"
        />
      </view>
      <!-- 跳转信息 -->
      <view class="ulbox">
        <view class="ul">
          <view
            class="li"
            :class="[
              { border_b: index < ulList.length - 1 },
              { ac: index === ulList.length - 1 },
            ]"
            v-for="(item, index) in ulList"
            :key="index + 1"
          >
            <template v-if="item.type === 'select'">
              <picker
                :disabled="
                  item.text.includes('生日') && store.userInfo?.birth
                    ? true
                    : false
                "
                @change="(e) => bindPickerChange(e, item)"
                value="value"
                :range="item.selectList"
                :mode="item.mode"
                range-key="text"
              >
                <view
                  class="libox"
                  :class="{ ac: index === ulList.length - 1 }"
                >
                  <view class="cen_text">
                    <text class="t1">{{ item.text }}</text>
                    <text :class="{ t2: index === ulList.length - 1 }">{{
                      item.text2
                    }}</text>
                  </view>
                  <!-- 箭头 -->
                  <view style="transform: translateY(4rpx)" v-if="!item.noTo">
                    <uni-icons color="#999" type="right" size="20"></uni-icons>
                  </view>
                </view>
              </picker>
            </template>

            <template v-else>
              <view
                class="libox"
                :class="{ ac: index === ulList.length - 1 }"
                @click="liFun(item)"
              >
                <view class="cen_text">
                  <text class="t1">{{ item.text }}</text>
                  <text :class="{ t2: index === ulList.length - 1 }">{{
                    item.text2
                  }}</text>
                </view>
                <!-- 箭头 -->
                <view style="transform: translateY(4rpx)" v-if="!item.noTo">
                  <uni-icons color="#999" type="right" size="20"></uni-icons>
                </view>
              </view>
            </template>
          </view>
        </view>
      </view>
      <!-- 文字 -->
      <view class="btext">
        <image :src="`${store.imgDomain}my_text.png`" mode="scaleToFill" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useCounterStore } from '@/store';
import { onLoad, onShow } from '@dcloudio/uni-app';
import request from '@/utils/request';

const store = useCounterStore();
const userInfo = ref({});
const array = ['中国', '美国', '巴西', '日本'];
//
const ulList = computed(() => [
  {
    text: '昵称',
    text2: store.userInfo?.nick_name,
    path: '/pages/my/myNickname',
    field: 'headimg',
  },
  {
    text: '性别',
    path: '',
    mode: 'selector',
    type: 'select',
    field: 'sex',
    text2: store.userInfo?.sex
      ? store.userInfo?.sex === 1
        ? '男'
        : '女'
      : '无',
    selectList: [
      { text: '男', value: '1' },
      { text: '女', value: '2' },
    ],
  },
  {
    text: store.userInfo?.birth
      ? '生日（已修改，不可再次修改）'
      : '生日（只能修改一次）',
    path: '',
    mode: 'date',
    type: 'select',
    field: 'birth',
    text2: store.userInfo?.birth || '无',
  },
  {
    text: '手机号码',
    text2: store.userInfo?.phone,
    path: '',
    noTo: true,
  },
  {
    text: '我的地址',
    text2: '新增/修改地址',
    path: '/pages/my/myaddress',
  },
]);

//
const liFun = (item) => {
  if (item.type) {
    if (item.type === 'logout') {
      logoutFun();
    } else if (item.type === 'phone') {
      handleCall();
    }
  } else {
    if (item.path)
      uni.navigateTo({
        url: item.path,
      });
  }
};

// 下拉选择
const bindPickerChange = (e, item) => {
  console.log('1111=>', e);
  let value = e.detail.value;
  if (item.field === 'sex') {
    value = +e.detail.value + 1;
  }
  doSaveUserBaseInfo(item.field, value);
};

// 投诉电话
const handleCall = () => {
  uni.makePhoneCall({
    phoneNumber: store.customerServicePhone, // 要拨打的电话号码（字符串类型）
    success: () => {
      console.log('拨打电话请求已发出');
    },
  });
};

// 退出登录
const logoutFun = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    confirmText: '确定', // 确认按钮文字
    cancelText: '取消', // 取消按钮文字
    success: (res) => {
      if (res.confirm) {
        store.outFun();
      }
    },
    fail: (err) => {
      console.error('显示模态框失败', err);
    },
  });
};

// 选择图片
const imgFun = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'], // 支持原图和压缩图
    sourceType: ['album', 'camera'], // 支持相册和相机
    success: (res) => {
      console.log('选中的图片=>', res);

      // 选中的图片临时路径数组
      onChooseAvatar(res.tempFilePaths[0]);
    },
    fail(err) {
      errData.value = err;
      console.log('选择失败=>', err);
    },
  });
};

const errData = ref({});
// 选择头像回调
const onChooseAvatar = (avatarUrl) => {
  uni.uploadFile({
    url: 'https://adm.jinjiangservice.com/index.php/wxapp/common/uploadCommonImage',
    method: 'POST',
    filePath: avatarUrl,
    formData: {
      file: avatarUrl,
    },
    header: {
      'Content-Type': 'multipart/form-data',
    },
    name: 'file',
    success: (res) => {
      console.log('上传的图片=>', res);
      doSaveUserBaseInfo('headimg', JSON.parse(res.data).data.path);
    },
    fail(err) {
      errData.value = err;
      console.log('上传失败=>', err);
    },
  });
};

// 保存个人资料修改
const doSaveUserBaseInfo = async (field, value) => {
  const datas = {
    field,
    value,
  };
  await request('wxapp/user/doSaveUserBaseInfo', datas, 'POST');
  store.userInfo[field] = value;
};

onShow(() => {
  userInfo.value = store.userInfo;
});
</script>

<style lang="scss" scoped>
.topl {
  position: absolute;
  top: -60rpx;
  left: 0;
  z-index: 0;
  image {
    width: 750rpx;
    height: 364rpx;
  }
}
.topinfo {
  position: relative;
  box-sizing: border-box;
  padding: 30rpx;
  display: flex;
  align-items: center;
  .yhimg {
    position: absolute;
    top: 0;
    left: 0;
    width: 750rpx;
    height: 127rpx;
    z-index: 0;
  }
  .hadeimg {
    display: block;
    margin: 20rpx auto;
    border: 1px solid #fff;
    border-radius: 50%;
    width: 125rpx;
    height: 125rpx;
    position: relative;
    z-index: 1;
  }
}
.ulbox {
  margin-top: -20rpx;
  padding: 20rpx;
  .ul {
    border: 1rpx solid #437ef6;
    border-radius: 20rpx;
    box-sizing: border-box;
    padding: 0 20rpx;
    background-color: #fff;
    .libox {
      display: flex;
      align-items: center;
      padding: 30rpx 20rpx;
      box-sizing: border-box;

      &.ac {
        padding-bottom: 35rpx;
      }
      .imgbox {
        width: 50rpx;
        height: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .img1 {
          width: 46rpx;
          height: 34rpx;
        }
        .img2 {
          width: 36rpx;
          height: 38rpx;
        }
        .img3 {
          width: 40rpx;
          height: 40rpx;
        }
        .img4 {
          width: 38rpx;
          height: 44rpx;
        }
        .img5 {
          width: 40rpx;
          height: 40rpx;
        }
        .img6 {
          width: 42rpx;
          height: 44rpx;
        }
      }
      .cen_text {
        padding: 0 10rpx;
        flex: 1;
        display: flex;
        justify-content: space-between;
        .t2 {
          color: $uni-text-color-grey;
        }
      }
    }
  }
}
.btext {
  position: relative;
  margin-top: 35rpx;
  display: flex;
  justify-content: center;
  &::after {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    left: 140rpx;
    transform: translateY(-50%);
    background-color: #73adff;
  }
  &::before {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    right: 140rpx;
    transform: translateY(-50%);
    background-color: #73adff;
  }
  image {
    position: relative;
    display: block;
    opacity: 0.6;
    width: 185rpx;
    height: 38rpx;
  }
}
</style>
